package com.lcq.springbootcreate.project.fliter;

import com.lcq.springbootcreate.project.ExceptionAndEnum.MallException;
import com.lcq.springbootcreate.project.ExceptionAndEnum.MallExceptionEnum;
import com.lcq.springbootcreate.project.common.Constant;
import com.lcq.springbootcreate.project.entity.User;
import com.lcq.springbootcreate.project.service.UserService;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(urlPatterns = ("/admin/*"), filterName = "adminFilter")
public class AdminFilter implements Filter {

    @Autowired
    UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 从session获取user
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        User currentuser = (User) session.getAttribute(Constant.MALL_USER);
        if (currentuser == null) {
            returnJson(servletResponse,"需要登录");
            return;
        }
        boolean isAdmin = userService.checkAdminRole(currentuser);
        if (isAdmin) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            returnJson(servletResponse,"不是管理员");
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private void returnJson(ServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            System.out.println(e.fillInStackTrace());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
